﻿using System;
using System.IO;
using QzEbook.AccessObject;
using QzEbook.BaseView;
using QzEbook.Common;

namespace qzEbook.webUI
{
    public partial class Delete : UserPage
    {
        private bool action = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            //用于判断用户是否拥有权限;
            this.checkUser();

            //删除一页;
            string pid = Request["Pid"] as string;
            if (pid != null)
            {
                if (!string.IsNullOrEmpty(Request["ok"]) && Request["ok"] == "1")
                {
                    action = deleteOnePage(int.Parse(pid));
                }
            }

            //删除一本电子书;
            string bid = Request["Bid"] as string;
            if (bid != null)
            {
                action = deleteOneBook(int.Parse(bid));
            }

            Response.Clear();

            if (action)
            {
                Response.Write("删除成功");
            }
            else
            {
                Response.Write("失败,可能为系统繁忙.(确认是你的电子书.)");
            }
            Response.End();
        }


        public bool deleteOnePage(int pid)
        {
            BookPage page = new BookPage();
            page.PageId = pid;
            page.UserId= userSession.Uid;
            string path = string.Format("../{0}{1}", Config.UserBookSavePath, page.selectPath());
            path = Server.MapPath(path);
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            return page.delete();
        }

        public bool deleteOneBook(int bid)
        {
            bool result = false;
            Book book = new Book();
            book.BookId = bid;
            book.EditorId = userSession.Uid;
            try
            {
                result = book.delete();
                string path = string.Format("../{0}{1}/{2}", Config.UserBookSavePath, book.EditorId, book.BookId);
                path = Server.MapPath(path);
                if (Directory.Exists(path))
                {
                    string[] files = Directory.GetFiles(path);
                    foreach (string file in files)
                    {
                        File.Delete(file);
                    }
                }
            }
            catch
            {
            }
            return result;
        }
    }
}
